package org.example.generics;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap;

public class Processor {

    private ConcurrentHashMap<String,BinlogHandler<?>> container = new ConcurrentHashMap<>();

    public <T> void register(BinlogHandler<T> handler){
        String key = handler.table().getDb() + "." + handler.table().getTable();
        container.put(key, handler);
    }

    public void process(String json) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonTable jsonTable = objectMapper.readValue(json,JsonTable.class);
        Table table = jsonTable.getTable();
        String key = table.getDb() +"."+ table.getTable();
        BinlogHandler<?> handler = container.get(key);
        Method[] methods = handler.getClass().getDeclaredMethods();
        Type type= methods[1].getGenericParameterTypes()[0];
        Object object = objectMapper.readValue(json,objectMapper.constructType(type));
        methods[1].invoke(handler,object);
        handler.handler((Binlog)object);
    }

}
